<?php
declare(strict_types=1);

namespace App\Console\Commands\Tasks;


use App\Models\MainDB\Gift;
use App\Models\MainDB\GiftWall\UserGiftWall;
use App\Models\MainDB\GiveGift;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ScriptGiftWallCommand extends Command
{

    protected $signature = 'script:gift-wall {type?}';
    protected $description = '修复礼物墙';

    public function __construct()
    {
        parent::__construct();
    }


    public function handle()
    {
        $type = $this->argument("type") == 'target' ? 'target' : 'give';

        if ($type == "target") { // 修复收礼礼物墙
            $group = ["gift_user", "gift_id"];
            $fields = [DB::raw("gift_user as user_id"), "gift_id", DB::raw("sum(number) as count")];
            $giftWallType = 1;
        } else { // 修复送礼礼物墙
            $group = ["user_id", "gift_id"];
            $fields = ["user_id", "gift_id", DB::raw("sum(number) as count")];
            $giftWallType = 2;
        }
        // 获取在礼物墙展示的礼物
        $gifts = Gift::query()->where('is_show_in_wall', 1)->get();
        $giftIds = $gifts->pluck('id');
        $query = GiveGift::query();
        $query->whereIn('gift_id', $giftIds);
        $query->groupBy($group);
        $query->select($fields);
        $models = $query->get();


        $models = $models->sortBy("user_id");
        $uniqueUserIds = $models->pluck('user_id')->unique();
        $data = [];

        foreach ($uniqueUserIds as $userId) {
            $giftWall = UserGiftWall::query()
                ->where('user_id', $userId)
                ->where('type', $giftWallType)
                ->groupBy(["user_id", "gift_id"])
                ->select(["user_id", "gift_id", DB::raw("sum(number) as count")])
                ->get();

            foreach ($giftWall as $value) {
                DB::beginTransaction();
                try {
                    $getGift = $models->where("user_id", $value->user_id)->where("gift_id", $value->gift_id)->first();
                    $getGiftCount = $getGift->count ?? 0;
                    $originCount = $value->count;
                    if ($getGiftCount != $value->count) {
                        $data[] = [
                            'user_id' => $value->user_id,
                            'gift_id' => $value->gift_id,
                            'count' => $value->count,
                            'real_count' => $getGiftCount
                        ];
                        // 置为空, 防止存在多条记录情况.
                        UserGiftWall::query()
                            ->where('user_id', $value->user_id)
                            ->where('gift_id', $value->gift_id)
                            ->where('type', $giftWallType)
                            ->update(['number' => 0]);
                        // 修改其中一条数量
                        $model = UserGiftWall::query()
                            ->where('user_id', $value->user_id)
                            ->where('gift_id', $value->gift_id)
                            ->where('type', $giftWallType)
                            ->first();
                        $model->number = $getGiftCount;
                        $model->save();
                        echo "[{$type}] 用户: {$userId}, 礼物id: {$value->gift_id}, 原礼物墙数量: {$originCount}, 更正为: {$getGiftCount}" . PHP_EOL;
                    }
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    continue;
                }
            }
        }
        echo "[{$type}] success" . PHP_EOL;
    }
}